package com.ch.clinking.activity;

import static android.app.PendingIntent.getActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.icu.util.Calendar;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.ch.clinking.ClinkingApplication;
import com.ch.clinking.R;
import com.ch.clinking.Utils.DownloadImage;
import com.ch.clinking.Utils.NetUtils.DoCallBack;
import com.ch.clinking.Utils.NetUtils.OkHttpUtil;
import com.ch.clinking.adapter.MerEditAdapter;
import com.ch.clinking.adapter.MerListViewAdapter;
import com.ch.clinking.adapter.SameKindAdapter;
import com.ch.clinking.adapter.SearchListAdapter;
import com.ch.clinking.adapter.StockChangedAdapter;
import com.ch.clinking.bean.ImageRequest;
import com.ch.clinking.bean.Merchandise;
import com.ch.clinking.bean.MerchandiseDto;
import com.ch.clinking.bean.Order;
import com.ch.clinking.bean.SameKind;
import com.ch.clinking.bean.Shop;
import com.ch.clinking.bean.SkuInfo;
import com.ch.clinking.bean.StockChanged;
import com.ch.clinking.databinding.ActivityEditMerStockBinding;
import com.ch.clinking.fragment.MerFragment;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

public class EditMerStockActivity extends AppCompatActivity {

    private ActivityEditMerStockBinding binding;
    private RecyclerView recyclerView;
    private Button commit;
    private Button batchButton;
    private MerchandiseDto merchandise;
    private MerEditAdapter merEditAdapter;
    private List<SkuInfo> skuInfoList;
    private RecyclerView.LayoutManager layoutManager;
    private ClinkingApplication app;
    private String skcId;
    private MerchandiseDto merchandiseCheck;

    private List<SameKind> sameKinds;

    private SameKindAdapter sameKindAdapter;

    // 图片
    private static final int PICK_IMAGE_REQUEST = 1;
    private Bitmap selectedImageBitmap;
    private final Handler handler = new Handler();
    private boolean uploadImg = false;


    private PopupWindow sizePopupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityEditMerStockBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        app = ClinkingApplication.getInstance();

        // 设置状态栏图标为深色
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        SimpleAdapter simpleAdapter;

        Intent intent = getIntent();
        skcId = (String) intent.getSerializableExtra("skcId");
        // 通过SKC获取该商品信息
        if (skcId != null) {

            getMerBySkcId();


        }

        binding.stockCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                showLoading();

                // 确保提交时商品库存未被其他人更新
                HashMap<String, String> mer = new HashMap<>();
                mer.put("skcId", merchandise.getSkcId());

                OkHttpUtil.getInstance().doPostForm("/mer/selectMerBySkcId", new DoCallBack() {
                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void onSuccess(String result) {
                        Log.d("selectMerBySkcId", "result:"+result);

                        merchandiseCheck= new Gson().fromJson(result, MerchandiseDto.class);

                        //判断是否被更改
                        if (!merchandiseCheck.equals(merchandise)) {
                            Toast.makeText(EditMerStockActivity.this, "商品库存已被修改，请重新提交", Toast.LENGTH_SHORT).show();
                            hideLoading();
                            EditMerStockActivity.this.finish();
                            return;
                        } else {
                            // 获取RecyclerView中各项的内容
                            for (int i = 0; i < merEditAdapter.getItemCount(); i++) {
                                checkTitle(merEditAdapter.skuInfoList.get(i).getTitle(), merEditAdapter.skuInfoList.get(i).getFinalNum());
                                Log.d("skuUpdate", i + ":" + merEditAdapter.skuInfoList.get(i).getTitle());
                            }

                            merchandise.setProductNumber(String.valueOf(binding.addSKCProductNum.getText()));
                            merchandise.setSkcId(String.valueOf(binding.merSkcId.getText()));
                            merchandise.setSpuId(String.valueOf(binding.editMerSpuId.getText()));
                            merchandise.setTitle(String.valueOf(binding.merTitle.getText()));
                            merchandise.setPrice(Double.parseDouble(String.valueOf(binding.merPrice.getText())));

                            //判断是否被更改
                            if (merchandiseCheck.equals(merchandise)) {
                                hideLoading();
                                EditMerStockActivity.this.finish();
                                return;
                            }

                            // 获取当前时间
                            Calendar calendar = Calendar.getInstance();
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
                            String formattedDateTime = formatter.format(calendar.getTime());

//                            merchandise.setFirstImage(merchandise.getSkcId() + "_" + formattedDateTime + ".jpg");


                            String merString = new Gson().toJson(merchandise);
                            Log.d("skuUpdate", String.valueOf(merchandise.getInHouseStock_M()));

                            OkHttpUtil.getInstance().doPostJson("/mer/updateMer", new DoCallBack() {
                                @Override
                                public void onSuccess(String result) {
                                    Log.d("skuUpdate", result);

                                    createChangedRecord();


                                    hideLoading();


                                    Intent resultIntent = new Intent();
                                    resultIntent.putExtra("updatedMerchandise", merchandise.getSkcId()); // 假设这是你需要传递的库存数据
                                    setResult(Activity.RESULT_OK, resultIntent);
                                    EditMerStockActivity.this.finish(); // 关闭当前Activity
                                }

                                @Override
                                public void onError(Exception e) {
                                    Log.d("skuUpdate", "error");
                                    Toast.makeText(EditMerStockActivity.this, "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
                                }
                            }, merString);
                        }


                        hideLoading();
                    }

                    @Override
                    public void onError(Exception e) {
                        Toast.makeText(EditMerStockActivity.this, "网络错误,获取商品失败,请稍后再试", Toast.LENGTH_SHORT).show();
                        hideLoading();
                    }
                }, mer);


            }
        });

        binding.stockDeleteMer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(EditMerStockActivity.this);
                builder.setTitle("确认删除");
                builder.setMessage("确定删除<" + merchandise.getTitle() + ">吗?");
                builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        HashMap<String, String> merMap = new HashMap<>();
                        merMap.put("skc", merchandise.getSkcId());
                        // 执行删除操作，例如从数据集中移除对应项
                        OkHttpUtil.getInstance().doPostForm("/mer/delete", new DoCallBack() {
                            @Override
                            public void onSuccess(String result) {
                                Log.d("Mer Delete", result);
//                                remove(getItem(position));
//                                merchandiseList.remove(position);
//                                List<Merchandise> update = new ArrayList<>();
//                                update.addAll(merchandiseList);
//                                update.remove(position);
//                                merchandiseList = update;
//                                notifyDataSetChanged();
                                dialog.dismiss();
                                EditMerStockActivity.this.finish();
                            }

                            @Override
                            public void onError(Exception e) {
                                Log.d("tag", "Mer Delete error");
                                Toast.makeText(EditMerStockActivity.this, "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
                            }
                        }, merMap);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        dialog.dismiss();
                    }
                });
                builder.show();
            }
        });


        binding.sizeInfoMer.setOnClickListener(new View.OnClickListener() {

            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onClick(View view) {
                View contentView = getLayoutInflater().inflate(R.layout.popup_size_table, null, false);
                backgroundAlpha(0.4f);

                TableLayout tableLayout = contentView.findViewById(R.id.tableLayout);
                Button addRowButton = contentView.findViewById(R.id.addRowButton);
                Button removeRowButton = contentView.findViewById(R.id.removeRowButton);
                Button addColumnButton = contentView.findViewById(R.id.addColumnButton);
                Button removeColumnButton = contentView.findViewById(R.id.removeColumnButton);
                Button submitButton = contentView.findViewById(R.id.submitSizeButton);
                EditText editWeight = contentView.findViewById(R.id.mer_weight);

                if (merchandise.getWeight() == null) {
                    editWeight.setText("0");
                }else {
                    editWeight.setText(String.valueOf(merchandise.getWeight()));
                }

                // 初始化表格
//                initializeTable(tableLayout);
                if (merchandise.getSizeInfo() == null){
                    // 添加表头
                    TableRow headerRow = new TableRow(EditMerStockActivity.this);
                    EditText editText = createEditTextWithFixedWidth("尺码表");
                    headerRow.addView(editText);
                    tableLayout.addView(headerRow);
                    Toast.makeText(EditMerStockActivity.this, String.valueOf(tableLayout.getChildCount()), Toast.LENGTH_SHORT).show();
                }else {
                    String[][] tableData = parseTableData(merchandise.getSizeInfo());
                    initializeTableFromData(tableLayout, tableData);
                }

                addRowButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        addRow(tableLayout);
                    }
                });

                removeRowButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        removeRow(tableLayout);
                    }
                });

                addColumnButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        addColumn(tableLayout);
                    }
                });

                removeColumnButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        removeColumn(tableLayout);
                    }
                });

                submitButton.setOnClickListener(new View.OnClickListener() {
                    @RequiresApi(api = Build.VERSION_CODES.M)
                    @Override
                    public void onClick(View v) {
                        submitTable(tableLayout, editWeight);
                        backgroundAlpha(1.0f);
                        sizePopupWindow.dismiss();
                    }
                });

                sizePopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
                sizePopupWindow.setFocusable(true);
                sizePopupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE)); // 设置背景颜色为白色
                sizePopupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);

                sizePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        backgroundAlpha(1.0f); // 弹窗关闭时恢复背景透明度
                    }
                });

//                TextView cancel = contentView.findViewById(R.id.batch_pop_cancel);
//                cancel.setOnClickListener(new View.OnClickListener() {
//                    @RequiresApi(api = Build.VERSION_CODES.M)
//                    @Override
//                    public void onClick(View view) {
////                        backgroundAlpha2(1.0f);
//                        sizePopupWindow.dismiss();
//                    }
//                });
            }
        });


        binding.batchStockSetting.setOnClickListener(new View.OnClickListener() {

            int operation = 1;
            PopupWindow popupWindow;

            @Override
            public void onClick(View view) {
                View contentView = getLayoutInflater().inflate(R.layout.popup_edit_batch_stock, null, false);


                backgroundAlpha(0.4f);
                TextView cancel = (TextView) contentView.findViewById(R.id.batch_pop_cancel);
                TextView confirm = (TextView) contentView.findViewById(R.id.batch_pop_confirm);
                RadioGroup batchGroup = (RadioGroup) contentView.findViewById(R.id.batch_add_reduce_button_group);
                RadioButton batchAddButton = (RadioButton) contentView.findViewById(R.id.batch_sku_add_button);
                EditText operateNum = (EditText) contentView.findViewById(R.id.batch_sku_operate_num);

                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        backgroundAlpha(1.0f);
                        popupWindow.dismiss();
                    }
                });

                confirm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        String num = String.valueOf(operateNum.getText());

                        int theOperateNum = 0;
                        if (!String.valueOf(operateNum.getText()).equals("")) {
                            theOperateNum = Integer.parseInt(String.valueOf(operateNum.getText()));
                        }

                        for (int i = 0; i < merEditAdapter.getItemCount(); i++) {
                            merEditAdapter.skuInfoList.get(i).setOperateNum(theOperateNum);
                            if (operation == 1) {
                                merEditAdapter.skuInfoList.get(i).setFinalNum(theOperateNum + merEditAdapter.skuInfoList.get(i).getStock());
                                merEditAdapter.skuInfoList.get(i).setOperation(1);
                            } else {
                                merEditAdapter.skuInfoList.get(i).setFinalNum(Math.max(merEditAdapter.skuInfoList.get(i).getStock() - theOperateNum, 0));
                                merEditAdapter.skuInfoList.get(i).setOperation(-1);
                            }
                        }
                        merEditAdapter.batch = merEditAdapter.getItemCount();
                        merEditAdapter.flash();

                        backgroundAlpha(1.0f);
                        popupWindow.dismiss();
                    }
                });

                batchGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        RadioButton radioButton = (RadioButton) group.findViewById(checkedId);


                        // 获取选中的单选按钮的文本内容
                        String selectedOption = radioButton.getText().toString();
                        if (selectedOption.equals("增")) {
                            operation = 1;

                        } else if (selectedOption.equals("减")) {
                            operation = -1;
                        }
                    }
                });
                popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
                //设置可以获取焦点
                popupWindow.setFocusable(true);
                // 这里是位置显示方式,在屏幕的侧
                popupWindow.showAtLocation(view, Gravity.CENTER, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

//                contentView.setOnTouchListener(new View.OnTouchListener() {
//                    @Override
//                    public boolean onTouch(View v, MotionEvent event) {
//                        if (popupWindow != null && popupWindow.isShowing()) {
//                            popupWindow.dismiss();
//
//                            backgroundAlpha(1.0f);
//                            popupWindow = null;
//                        }
//                        return false;
//                    }
//                });
            }
        });

        binding.editMerStockAddSize.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showSizePickerDialog();
            }
        });

        binding.detailStockChangedRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                showLoading();

                HashMap<String, String> mer = new HashMap<>();
                mer.put("skcId", merchandise.getSkcId());

                OkHttpUtil.getInstance().doPostForm("/stock/selectStockChangedListBySkcId", new DoCallBack() {
                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void onSuccess(String result) {

                        StockChanged[] stockChangedList = new Gson().fromJson(result, StockChanged[].class);
                        hideLoading();

                        showStockRecordDialog(Arrays.asList(stockChangedList));


                    }

                    @Override
                    public void onError(Exception e) {
                        Toast.makeText(EditMerStockActivity.this, "网络错误,获取库存记录失败,请稍后再试", Toast.LENGTH_SHORT).show();
                        hideLoading();
                    }
                }, mer);


            }
        });

        binding.editMerSameKind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                showLoading();

                HashMap<String, String> mer = new HashMap<>();
                mer.put("skcId", merchandise.getSkcId());

                OkHttpUtil.getInstance().doPostForm("/mer/selectSameKindListByMainSkcId", new DoCallBack() {
                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void onSuccess(String result) {

                        sameKinds = Arrays.asList(new Gson().fromJson(result, SameKind[].class));
                        hideLoading();

                        showSameKindDialog();


                    }

                    @Override
                    public void onError(Exception e) {
                        Toast.makeText(EditMerStockActivity.this, "网络错误,获取库存记录失败,请稍后再试", Toast.LENGTH_SHORT).show();
                        hideLoading();
                    }
                }, mer);

            }
        });

//        binding.editMerStockBatchAddReduceButtonGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
//
//
//                // 获取选中的单选按钮的文本内容
//                String selectedOption = radioButton.getText().toString();
//                if (selectedOption.equals("增")) {
//                    for (SkuInfo skuInfo : merEditAdapter.skuInfoList) {
//                        skuInfo.setOperation(1);
//                    }
//
//                } else if (selectedOption.equals("减")) {
//                    for (SkuInfo skuInfo : merEditAdapter.skuInfoList) {
//                        skuInfo.setOperation(-1);
//                    }
//                }
//
//                merEditAdapter.flash();
//            }
//        });

//        binding.merImg.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                openGallery();
//            }
//        });

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void createChangedRecord() {

        StockChanged stockChanged = new StockChanged(app.user.getAccount(), app.user.getNickName(), merchandise.getSkcId());

        calculateChanged(stockChanged ,merchandiseCheck, merchandise);

        Log.d("stockChanged", String.valueOf(stockChanged));

        String stockChangedString = new Gson().toJson(stockChanged);

        OkHttpUtil.getInstance().doPostJson("/stock/stockChangedRecord", new DoCallBack() {
            @Override
            public void onSuccess(String result) {
                Log.d("stockChangedRecord", result);

            }

            @Override
            public void onError(Exception e) {
                Log.d("stockChangedRecord", "error");
                Toast.makeText(EditMerStockActivity.this, "网络错误,库存记录创建失败,请稍后再试", Toast.LENGTH_SHORT).show();
            }
        }, stockChangedString);

    }

    private void calculateChanged(StockChanged stockChanged,MerchandiseDto merchandiseCheck, MerchandiseDto merchandise) {

        stockChanged.setChange_XXS(merchandise.getInHouseStock_XXS() - merchandiseCheck.getInHouseStock_XXS());
        stockChanged.setChange_XS(merchandise.getInHouseStock_XS() - merchandiseCheck.getInHouseStock_XS());
        stockChanged.setChange_S(merchandise.getInHouseStock_S() - merchandiseCheck.getInHouseStock_S());
        stockChanged.setChange_M(merchandise.getInHouseStock_M() - merchandiseCheck.getInHouseStock_M());
        stockChanged.setChange_L(merchandise.getInHouseStock_L() - merchandiseCheck.getInHouseStock_L());
        stockChanged.setChange_XL(merchandise.getInHouseStock_XL() - merchandiseCheck.getInHouseStock_XL());
        stockChanged.setChange_XXL(merchandise.getInHouseStock_XXL() - merchandiseCheck.getInHouseStock_XXL());
        stockChanged.setChange_Plus_0XL(merchandise.getInHouseStock_Plus_0XL() - merchandiseCheck.getInHouseStock_Plus_0XL());
        stockChanged.setChange_Plus_1XL(merchandise.getInHouseStock_Plus_1XL() - merchandiseCheck.getInHouseStock_Plus_1XL());
        stockChanged.setChange_Plus_2XL(merchandise.getInHouseStock_Plus_2XL() - merchandiseCheck.getInHouseStock_Plus_2XL());
        stockChanged.setChange_Plus_3XL(merchandise.getInHouseStock_Plus_3XL() - merchandiseCheck.getInHouseStock_Plus_3XL());
        stockChanged.setChange_Plus_4XL(merchandise.getInHouseStock_Plus_4XL() - merchandiseCheck.getInHouseStock_Plus_4XL());
        stockChanged.setChange_Plus_5XL(merchandise.getInHouseStock_Plus_5XL() - merchandiseCheck.getInHouseStock_Plus_5XL());
        stockChanged.setChange_Plus_6XL(merchandise.getInHouseStock_Plus_6XL() - merchandiseCheck.getInHouseStock_Plus_6XL());

        stockChanged.setActivate_XXS(merchandise.isActivate_XXS());
        stockChanged.setActivate_XS(merchandise.isActivate_XS());
        stockChanged.setActivate_S(merchandise.isActivate_S());
        stockChanged.setActivate_M(merchandise.isActivate_M());
        stockChanged.setActivate_L(merchandise.isActivate_L());
        stockChanged.setActivate_XL(merchandise.isActivate_XL());
        stockChanged.setActivate_XXL(merchandise.isActivate_XXL());
        stockChanged.setActivate_Plus_0XL(merchandise.isActivate_Plus_0XL());
        stockChanged.setActivate_Plus_1XL(merchandise.isActivate_Plus_1XL());
        stockChanged.setActivate_Plus_2XL(merchandise.isActivate_Plus_2XL());
        stockChanged.setActivate_Plus_3XL(merchandise.isActivate_Plus_3XL());
        stockChanged.setActivate_Plus_4XL(merchandise.isActivate_Plus_4XL());
        stockChanged.setActivate_Plus_5XL(merchandise.isActivate_Plus_5XL());
        stockChanged.setActivate_Plus_6XL(merchandise.isActivate_Plus_6XL());

        stockChanged.setInHouseStock_XXS(merchandise.getInHouseStock_XXS());
        stockChanged.setInHouseStock_XS(merchandise.getInHouseStock_XS());
        stockChanged.setInHouseStock_S(merchandise.getInHouseStock_S());
        stockChanged.setInHouseStock_M(merchandise.getInHouseStock_M());
        stockChanged.setInHouseStock_L(merchandise.getInHouseStock_L());
        stockChanged.setInHouseStock_XL(merchandise.getInHouseStock_XL());
        stockChanged.setInHouseStock_XXL(merchandise.getInHouseStock_XXL());
        stockChanged.setInHouseStock_Plus_0XL(merchandise.getInHouseStock_Plus_0XL());
        stockChanged.setInHouseStock_Plus_1XL(merchandise.getInHouseStock_Plus_1XL());
        stockChanged.setInHouseStock_Plus_2XL(merchandise.getInHouseStock_Plus_2XL());
        stockChanged.setInHouseStock_Plus_3XL(merchandise.getInHouseStock_Plus_3XL());
        stockChanged.setInHouseStock_Plus_4XL(merchandise.getInHouseStock_Plus_4XL());
        stockChanged.setInHouseStock_Plus_5XL(merchandise.getInHouseStock_Plus_5XL());
        stockChanged.setInHouseStock_Plus_6XL(merchandise.getInHouseStock_Plus_6XL());

    }

    private void getMerBySkcId() {
        // 获取订单TAG列表
        HashMap<String, String> mer = new HashMap<>();
        mer.put("skcId", skcId);

        OkHttpUtil.getInstance().doPostForm("/mer/selectMerBySkcId", new DoCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onSuccess(String result) {
                Log.d("selectMerBySkcId", "result:"+result);

                merchandise = new Gson().fromJson(result, MerchandiseDto.class);

                skuInfoList = new ArrayList<>();
                setMerMap(merchandise);
                merEditAdapter = new MerEditAdapter(EditMerStockActivity.this, skuInfoList);
                //            simpleAdapter = new SimpleAdapter(EditMerStockActivity.this, data, R.layout.list_sku_layout, new String[]{"sku_title", "sku_stock", "sku_stock"}, new int[]{R.id.sku_title, R.id.sku_stock, R.id.sku_final_num});
                binding.skuStockList.setAdapter(merEditAdapter);
                layoutManager = new LinearLayoutManager(EditMerStockActivity.this);
                binding.skuStockList.setLayoutManager(layoutManager);
                int totalStock = 0;
                for (int i = 0; i < skuInfoList.size(); i++) {
                    totalStock += skuInfoList.get(i).getStock();
                }
                binding.merTitle.setText(merchandise.getTitle());
                binding.merSkcId.setText(merchandise.getSkcId());
                binding.editMerSpuId.setText(merchandise.getSpuId());
                binding.merNowStock.setText(String.valueOf(totalStock));
                binding.addSKCProductNum.setText(merchandise.getProductNumber());
                binding.merPrice.setText(String.valueOf(merchandise.getPrice()));

                // 设置默认占位图片
                Glide.with(EditMerStockActivity.this)
                        .load(R.drawable.appicon)
                        .into(binding.merImg);

                // 加载图片
                Glide.with(EditMerStockActivity.this)
                        .load(OkHttpUtil.getInstance().getIMG_URL() + merchandise.getFirstImage())
                        .placeholder(R.drawable.appicon)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)  // 缓存策略：缓存原始图片和转换后的图片
                        .thumbnail(0.5f)  // 缩略图大小
                        .error(R.drawable.appicon)
                        .into(binding.merImg);

                hideLoading();
            }

            @Override
            public void onError(Exception e) {
                Toast.makeText(EditMerStockActivity.this, "网络错误,获取商品失败,请稍后再试", Toast.LENGTH_SHORT).show();
                hideLoading();
            }
        }, mer);
    }

    private void showSameKindDialog() {
        // 创建Dialog
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("同款SKC");

        // 加载布局
        View dialogView = LayoutInflater.from(this).inflate(R.layout.popup_same_kind, null);
        builder.setView(dialogView);

        // 设置RecyclerView
        RecyclerView recyclerView = dialogView.findViewById(R.id.popup_same_kind_stock_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // 设置RecyclerView
        Button button = dialogView.findViewById(R.id.popup_same_kind_Line1_add_skc_btn);
        EditText skcEditText = dialogView.findViewById(R.id.popup_same_kind_Line1_add_skc);

//        // 添加分隔线
//        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), LinearLayoutManager.VERTICAL);
//        dividerItemDecoration.setDrawable(ContextCompat.getDrawable(this, R.drawable.divider));
//        recyclerView.addItemDecoration(dividerItemDecoration);

        sameKindAdapter = new SameKindAdapter(this, sameKinds);
        recyclerView.setAdapter(sameKindAdapter);

        // 显示Dialog
        builder.setPositiveButton("OK", (dialog, which) -> dialog.dismiss());
        builder.show();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String skc = skcEditText.getText().toString();

                if (skc.isEmpty()) {
                    return;
                }

                showLoading();


                HashMap<String, String> selectSameKind = new HashMap<>();
                selectSameKind.put("skcId", skc);


                OkHttpUtil.getInstance().doPostForm("/mer/selectSameKindBySKC", new DoCallBack() {
                    @Override
                    public void onSuccess(String result) {
                        Log.d("selectSameKindBySKC", "result:" + result);


                        Log.d("selectBySKC", result);

                        // 使用 Gson 解析 JSON 字符串
                        Gson gson = new Gson();
                        JsonObject data = gson.fromJson(result, JsonObject.class);

                        // 获取msg字段的值
                        String code = data.get("code").getAsString();

//                                remove(getItem(position));
//                                merchandiseList.remove(position);
//                                List<Merchandise> update = new ArrayList<>();
//                                update.addAll(merchandiseList);
//                                update.remove(position);
//                                merchandiseList = update;
//                                notifyDataSetChanged();
                        Log.d("selectSameKindBySKC", code);
                        if (code.equals("500")) {
                            Toast.makeText(EditMerStockActivity.this, "此SKC已存在，添加失败", Toast.LENGTH_SHORT).show();
                            hideLoading();
                        }else {

                            SameKind sameKindCreate = new SameKind();
                            sameKindCreate.setSkcId(skc);
                            sameKindCreate.setMainSkcId(merchandise.getSkcId());

                            String sameKindString = new Gson().toJson(sameKindCreate);

                            OkHttpUtil.getInstance().doPostJson("/mer/updateSameKind", new DoCallBack() {
                                @SuppressLint("NotifyDataSetChanged")
                                @Override
                                public void onSuccess(String result) {

                                    HashMap<String, String> mer = new HashMap<>();
                                    mer.put("skcId", merchandise.getSkcId());

                                    OkHttpUtil.getInstance().doPostForm("/mer/selectSameKindListByMainSkcId", new DoCallBack() {
                                        @RequiresApi(api = Build.VERSION_CODES.O)
                                        @Override
                                        public void onSuccess(String result) {

                                            sameKinds = Arrays.asList(new Gson().fromJson(result, SameKind[].class));
                                            sameKindAdapter.sameKindList = sameKinds;
                                            sameKindAdapter.notifyDataSetChanged();
                                            hideLoading();

                                        }

                                        @Override
                                        public void onError(Exception e) {
                                            Toast.makeText(EditMerStockActivity.this, "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
                                            hideLoading();
                                        }
                                    }, mer);



                                }

                                @Override
                                public void onError(Exception e) {
                                    Log.d("stockChangedRecord", "error");
                                    Toast.makeText(EditMerStockActivity.this, "网络错误,库存记录创建失败,请稍后再试", Toast.LENGTH_SHORT).show();
                                }
                            }, sameKindString);

                        }






                    }

                    @Override
                    public void onError(Exception e) {
                        Toast.makeText(EditMerStockActivity.this, "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
                        hideLoading();
                    }
                }, selectSameKind);


            }
        });

    }


    private void showStockRecordDialog(List<StockChanged> stockChangedList) {
        // 创建Dialog
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("库存变更记录");

        // 加载布局
        View dialogView = LayoutInflater.from(this).inflate(R.layout.popup_stock_changed_record, null);
        builder.setView(dialogView);

        // 设置RecyclerView
        RecyclerView recyclerView = dialogView.findViewById(R.id.popup_stock_changed_stock_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

//        // 添加分隔线
//        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), LinearLayoutManager.VERTICAL);
//        dividerItemDecoration.setDrawable(ContextCompat.getDrawable(this, R.drawable.divider));
//        recyclerView.addItemDecoration(dividerItemDecoration);

        StockChangedAdapter adapter = new StockChangedAdapter(this, stockChangedList);
        recyclerView.setAdapter(adapter);

        // 显示Dialog
        builder.setPositiveButton("OK", (dialog, which) -> dialog.dismiss());
        builder.show();
    }

    private void showSizePickerDialog() {
        // 创建Dialog
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("增加尺码");

        // 使用LayoutInflater加载自定义布局
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_edit_mer_add_size, null);
        builder.setView(dialogView);

        // 获取输入框和按钮
        RelativeLayout editMerNormalSizeContent = dialogView.findViewById(R.id.edit_mer_normal_size_content);
        RelativeLayout editMerPlusSizeContent = dialogView.findViewById(R.id.edit_mer_plus_size_content);
        Button btnCancel = dialogView.findViewById(R.id.dialog_edit_mer_add_size_BtnCancel);
        Button btnConfirm = dialogView.findViewById(R.id.dialog_edit_mer_add_size_BtnConfirm);

        // 初始化标码 CheckBox
        CheckBox checkBoxXXS = dialogView.findViewById(R.id.edit_checkBoxXXS);
        CheckBox checkBoxXS = dialogView.findViewById(R.id.edit_checkBoxXS);
        CheckBox checkBoxS = dialogView.findViewById(R.id.edit_checkBoxS);
        CheckBox checkBoxM = dialogView.findViewById(R.id.edit_checkBoxM);
        CheckBox checkBoxL = dialogView.findViewById(R.id.edit_checkBoxL);
        CheckBox checkBoxXL = dialogView.findViewById(R.id.edit_checkBoxXL);
        CheckBox checkBoxXXL = dialogView.findViewById(R.id.edit_checkBoxXXL);

        // 初始化大码 CheckBox
        CheckBox checkBox0XL = dialogView.findViewById(R.id.edit_checkBox0XL);
        CheckBox checkBox1XL = dialogView.findViewById(R.id.edit_checkBox1XL);
        CheckBox checkBox2XL = dialogView.findViewById(R.id.edit_checkBox2XL);
        CheckBox checkBox3XL = dialogView.findViewById(R.id.edit_checkBox3XL);
        CheckBox checkBox4XL = dialogView.findViewById(R.id.edit_checkBox4XL);
        CheckBox checkBox5XL = dialogView.findViewById(R.id.edit_checkBox5XL);
        CheckBox checkBox6XL = dialogView.findViewById(R.id.edit_checkBox6XL);




        if (app.shopList.get(app.shopPosition).getShopType().equals("标码")) {
            editMerNormalSizeContent.setVisibility(View.VISIBLE);
        } else {
            editMerPlusSizeContent.setVisibility(View.VISIBLE);
        }

        // 创建并显示Dialog
        AlertDialog dialog = builder.create();
        dialog.show();

        // 设置取消按钮点击事件
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        // 设置确认按钮点击事件
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (app.shopList.get(app.shopPosition).getShopType().equals("标码")) {
                    if (checkBoxXXS.isChecked()) {
                        merchandise.setActivate_XXS(true);
                    }
                    if (checkBoxXS.isChecked()) {
                        merchandise.setActivate_XS(true);
                    }
                    if (checkBoxS.isChecked()) {
                        merchandise.setActivate_S(true);
                    }
                    if (checkBoxM.isChecked()) {
                        merchandise.setActivate_M(true);
                    }
                    if (checkBoxL.isChecked()) {
                        merchandise.setActivate_L(true);
                    }
                    if (checkBoxXL.isChecked()) {
                        merchandise.setActivate_XL(true);
                    }
                    if (checkBoxXXL.isChecked()) {
                        merchandise.setActivate_XXL(true);
                    }
                } else {
                    if (checkBox0XL.isChecked()) {
                        merchandise.setActivate_Plus_0XL(true);
                    }
                    if (checkBox1XL.isChecked()) {
                        merchandise.setActivate_Plus_1XL(true);
                    }
                    if (checkBox2XL.isChecked()) {
                        merchandise.setActivate_Plus_2XL(true);
                    }
                    if (checkBox3XL.isChecked()) {
                        merchandise.setActivate_Plus_3XL(true);
                    }
                    if (checkBox4XL.isChecked()) {
                        merchandise.setActivate_Plus_4XL(true);
                    }
                    if (checkBox5XL.isChecked()) {
                        merchandise.setActivate_Plus_5XL(true);
                    }
                    if (checkBox6XL.isChecked()) {
                        merchandise.setActivate_Plus_6XL(true);
                    }
                }

                String merString = new Gson().toJson(merchandise);

                OkHttpUtil.getInstance().doPostJson("/mer/updateMer", new DoCallBack() {
                    @Override
                    public void onSuccess(String result) {

                        dialog.dismiss();
                        Log.d("updateMer", result);
                        getMerBySkcId();

                    }

                    @Override
                    public void onError(Exception e) {
                        Log.d("skuUpdate", "error");
                        Toast.makeText(EditMerStockActivity.this, "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
                    }
                }, merString);


            }
        });
    }


//    @RequiresApi(api = Build.VERSION_CODES.M)
//    private void backgroundAlpha2(float alpha) {
//        ViewGroup root = findViewById(android.R.id.content);
//        root.getForeground().setAlpha((int) (alpha * 255));
//    }

    private void initializeTable(TableLayout tableLayout) {
//        if (merchandise.getSizeInfo() == null){
//            System.out.println("**********************************************************************************************************************************************************************************************");
//        }else {
//
//
//
//        }
//        String[] headers = {"尺码", "腰围全围（cm）", "臀围全围（cm）", "裤长（cm）"};
//        addHeader(tableLayout, headers);
//        addRow(tableLayout, new String[]{"S", "67", "98", "100"});
//        addRow(tableLayout, new String[]{"M", "71", "102", "101"});
//        addRow(tableLayout, new String[]{"L", "77", "108", "102"});
//        addRow(tableLayout, new String[]{"XL", "83", "114", "103"});
//        addRow(tableLayout, new String[]{"XXL", "89", "120", "104"});
    }

    private void initializeTableFromData(TableLayout tableLayout, String[][] tableData) {
        tableLayout.removeAllViews(); // 清空现有表格内容

        // 添加表头
        if (tableData.length > 0) {
            TableRow headerRow = new TableRow(this);
            for (String header : tableData[0]) {
                EditText editText = createEditTextWithFixedWidth("");
                editText.setText(header);
//                editText.setLayoutParams(new TableRow.LayoutParams(100, ViewGroup.LayoutParams.WRAP_CONTENT)); // 设置固定宽度，例如100dp
                headerRow.addView(editText);
            }
            tableLayout.addView(headerRow);
        }

        // 添加数据行
        for (int i = 1; i < tableData.length; i++) {
            TableRow row = new TableRow(this);
            for (String cell : tableData[i]) {
                EditText editText = createEditTextWithFixedWidth("");
                editText.setText(cell);
                row.addView(editText);
            }
            tableLayout.addView(row);
        }

    }

    private String[][] parseTableData(String tableData) {
        String[] rows = tableData.split("\n");
        String[][] parsedData = new String[rows.length][];
        for (int i = 0; i < rows.length; i++) {
            parsedData[i] = rows[i].split("\t");
        }
        return parsedData;
    }

    private void addHeader(TableLayout tableLayout, String[] headers) {
        TableRow headerRow = new TableRow(this);
        for (String header : headers) {
            EditText editText = new EditText(this);
            editText.setText(header);
            headerRow.addView(editText);
        }
        tableLayout.addView(headerRow);
    }

    private void addRow(TableLayout tableLayout) {
        TableRow newRow = new TableRow(this);
        int columnCount = ((TableRow) tableLayout.getChildAt(0)).getChildCount();
        for (int i = 0; i < columnCount; i++) {
            EditText editText = createEditTextWithFixedWidth("");
            newRow.addView(editText);
//            editText.setLayoutParams(new TableRow.LayoutParams(100, ViewGroup.LayoutParams.WRAP_CONTENT)); // 设置固定宽度，例如100dp
        }
        tableLayout.addView(newRow);
        Toast.makeText(EditMerStockActivity.this, String.valueOf(tableLayout.getChildCount()), Toast.LENGTH_SHORT).show();
    }

    private EditText createEditTextWithFixedWidth(String text) {
        EditText editText = new EditText(this);
        editText.setText(text);
        editText.setLayoutParams(new TableRow.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)); // 设置宽度为1权重，实现均分
        return editText;
    }

//    private void addRow(TableLayout tableLayout, String[] rowData) {
//        TableRow newRow = new TableRow(this);
//        for (String data : rowData) {
//            EditText editText = new EditText(this);
//            editText.setText(data);
//            newRow.addView(editText);
//        }
//        tableLayout.addView(newRow);
//    }

    private void addColumn(TableLayout tableLayout) {
        int rowCount = tableLayout.getChildCount();
        for (int i = 0; i < rowCount; i++) {
            TableRow row = (TableRow) tableLayout.getChildAt(i);
            EditText editText = createEditTextWithFixedWidth("");
            row.addView(editText);
        }
        Toast.makeText(EditMerStockActivity.this, String.valueOf(((TableRow) tableLayout.getChildAt(0)).getChildCount()), Toast.LENGTH_SHORT).show();

    }

    private void removeRow(TableLayout tableLayout) {
        int rowCount = tableLayout.getChildCount();
        if (rowCount > 1) { // 保留至少一个表头行
            tableLayout.removeViewAt(rowCount - 1);
        }
    }

    private void removeColumn(TableLayout tableLayout) {
        int rowCount = tableLayout.getChildCount();
        if (rowCount > 0) {
            TableRow headerRow = (TableRow) tableLayout.getChildAt(0);
            int columnCount = headerRow.getChildCount();
            if (columnCount > 1) { // 保留至少一个列
                for (int i = 0; i < rowCount; i++) {
                    TableRow row = (TableRow) tableLayout.getChildAt(i);
                    row.removeViewAt(columnCount - 1);
                }
            }
        }
    }

    private void submitTable(TableLayout tableLayout, EditText editWeight) {
        int rowCount = tableLayout.getChildCount();
        int columnCount = ((TableRow) tableLayout.getChildAt(0)).getChildCount();

        StringBuilder tableData = new StringBuilder();
        for (int i = 0; i < rowCount; i++) {
            TableRow row = (TableRow) tableLayout.getChildAt(i);
            for (int j = 0; j < columnCount; j++) {
                View view = row.getChildAt(j);
                if (view instanceof EditText) {
                    EditText editText = (EditText) view;
                    tableData.append(editText.getText().toString()).append("\t");
                } else if (view instanceof TextView) {
                    TextView textView = (TextView) view;
                    tableData.append(textView.getText().toString()).append("\t");
                } else {
                    tableData.append("未知视图类型").append("\t"); // 处理未知视图类型
                    Log.e("submitTable", "未知视图类型: " + view.getClass().getName());
                }
            }
            tableData.append("\n");
        }

        // 处理表格数据 (例如：发送到服务器，保存到文件等)
        Toast.makeText(this, tableData.toString(), Toast.LENGTH_LONG).show();
        System.out.println(tableData.toString());
        merchandise.setSizeInfo(tableData.toString());

        merchandise.setWeight(Integer.parseInt(editWeight.getText().toString()));

        String merString = new Gson().toJson(merchandise);

        OkHttpUtil.getInstance().doPostJson("/mer/updateMer", new DoCallBack() {
            @Override
            public void onSuccess(String result) {

                Log.d("skuUpdate", result);

            }

            @Override
            public void onError(Exception e) {
                Log.d("skuUpdate", "error");
                Toast.makeText(EditMerStockActivity.this, "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
            }
        }, merString);

    }


    /**
     * 添加遮盖层的方法
     */
    private void backgroundAlpha(float f) {
        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.alpha = f;
        this.getWindow().setAttributes(lp);
    }

    private void checkTitle(String title, int stock) {
        Log.d("skuUpdate", title + " " + String.valueOf(title.equals("M")) + " " + stock);
        if (title.equals("XXS")) {
            merchandise.setInHouseStock_XXS(Math.max(stock, 0));
        }
        if (title.equals("XS")) {
            merchandise.setInHouseStock_XS(Math.max(stock, 0));
        }
        if (title.equals("S")) {
            merchandise.setInHouseStock_S(Math.max(stock, 0));
        }
        if (title.equals("M")) {

            merchandise.setInHouseStock_M(Math.max(stock, 0));
        }
        if (title.equals("L")) {
            merchandise.setInHouseStock_L(Math.max(stock, 0));
        }
        if (title.equals("XL")) {
            merchandise.setInHouseStock_XL(Math.max(stock, 0));
        }
        if (title.equals("XXL")) {
            merchandise.setInHouseStock_XXL(Math.max(stock, 0));
        }
        if (title.equals("0XL")) {
            merchandise.setInHouseStock_Plus_0XL(Math.max(stock, 0));
        }
        if (title.equals("1XL")) {
            merchandise.setInHouseStock_Plus_1XL(Math.max(stock, 0));
        }
        if (title.equals("2XL")) {
            merchandise.setInHouseStock_Plus_2XL(Math.max(stock, 0));
        }
        if (title.equals("3XL")) {
            merchandise.setInHouseStock_Plus_3XL(Math.max(stock, 0));
        }
        if (title.equals("4XL")) {
            merchandise.setInHouseStock_Plus_4XL(Math.max(stock, 0));
        }
        if (title.equals("5XL")) {
            merchandise.setInHouseStock_Plus_5XL(Math.max(stock, 0));
        }
        if (title.equals("6XL")) {
            merchandise.setInHouseStock_Plus_6XL(Math.max(stock, 0));
        }
    }

    private void setMerMap(MerchandiseDto merchandise) {
        if (merchandise.isActivate_XXS()) {
            SkuInfo skuInfo = new SkuInfo("XXS", merchandise.getInHouseStock_XXS(), merchandise.getFirstImage());
            skuInfoList.add(skuInfo);
        }
        if (merchandise.isActivate_XS()) {
            SkuInfo skuInfo = new SkuInfo("XS", merchandise.getInHouseStock_XS(), merchandise.getFirstImage());
            skuInfoList.add(skuInfo);
        }
        if (merchandise.isActivate_S()) {
            SkuInfo skuInfo = new SkuInfo("S", merchandise.getInHouseStock_S(), merchandise.getFirstImage());
            skuInfoList.add(skuInfo);
        }
        if (merchandise.isActivate_M()) {
            SkuInfo skuInfo = new SkuInfo("M", merchandise.getInHouseStock_M(), merchandise.getFirstImage());
            skuInfoList.add(skuInfo);
        }
        if (merchandise.isActivate_L()) {
            SkuInfo skuInfo = new SkuInfo("L", merchandise.getInHouseStock_L(), merchandise.getFirstImage());
            skuInfoList.add(skuInfo);
        }
        if (merchandise.isActivate_XL()) {
            SkuInfo skuInfo = new SkuInfo("XL", merchandise.getInHouseStock_XL(), merchandise.getFirstImage());
            skuInfoList.add(skuInfo);
        }
        if (merchandise.isActivate_XXL()) {
            SkuInfo skuInfo = new SkuInfo("XXL", merchandise.getInHouseStock_XXL(), merchandise.getFirstImage());
            skuInfoList.add(skuInfo);
        }
        if (merchandise.isActivate_Plus_0XL()) {
            SkuInfo skuInfo = new SkuInfo("0XL", merchandise.getInHouseStock_Plus_0XL(), merchandise.getFirstImage());
            skuInfoList.add(skuInfo);
        }
        if (merchandise.isActivate_Plus_1XL()) {
            SkuInfo skuInfo = new SkuInfo("1XL", merchandise.getInHouseStock_Plus_1XL(), merchandise.getFirstImage());
            skuInfoList.add(skuInfo);
        }
        if (merchandise.isActivate_Plus_2XL()) {
            SkuInfo skuInfo = new SkuInfo("2XL", merchandise.getInHouseStock_Plus_2XL(), merchandise.getFirstImage());
            skuInfoList.add(skuInfo);
        }
        if (merchandise.isActivate_Plus_3XL()) {
            SkuInfo skuInfo = new SkuInfo("3XL", merchandise.getInHouseStock_Plus_3XL(), merchandise.getFirstImage());
            skuInfoList.add(skuInfo);
        }
        if (merchandise.isActivate_Plus_4XL()) {
            SkuInfo skuInfo = new SkuInfo("4XL", merchandise.getInHouseStock_Plus_4XL(), merchandise.getFirstImage());
            skuInfoList.add(skuInfo);
        }
        if (merchandise.isActivate_Plus_5XL()) {
            SkuInfo skuInfo = new SkuInfo("5XL", merchandise.getInHouseStock_Plus_5XL(), merchandise.getFirstImage());
            skuInfoList.add(skuInfo);
        }
        if (merchandise.isActivate_Plus_6XL()) {
            SkuInfo skuInfo = new SkuInfo("6XL", merchandise.getInHouseStock_Plus_6XL(), merchandise.getFirstImage());
            skuInfoList.add(skuInfo);
        }
    }

    private void showLoading() {
        binding.EditMerStockLoadingProgressBar.setVisibility(View.VISIBLE);
        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
    }

    private void hideLoading() {
        binding.EditMerStockLoadingProgressBar.setVisibility(View.GONE);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
    }


//    private void openGallery() {
//        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        startActivityForResult(intent, PICK_IMAGE_REQUEST);
////        registerForActivityResult(intent, PICK_IMAGE_REQUEST)
//    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//
//        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
//            Uri selectedImageUri = data.getData();
//            try {
//                InputStream inputStream = getContentResolver().openInputStream(selectedImageUri);
//                selectedImageBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
//                binding.merImg.setImageBitmap(selectedImageBitmap);
//                uploadImg = true;
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }

//    private class UploadImageTask extends AsyncTask<Void, Void, String> {
//        @Override
//        protected String doInBackground(Void... voids) {
//            // Convert the Bitmap to a base64-encoded string
//            String imageData = bitmapToBase64(selectedImageBitmap);
//
//            // Perform your HTTP request here to upload the image to the server
//            // For example, you can use HttpClient or HttpURLConnection
//
//            // Dummy example: Send the base64-encoded image data to a server
//            String serverResponse = sendImageToServer(imageData);
//
//            return serverResponse;
//        }
//
//        @Override
//        protected void onPostExecute(String result) {
//            // Handle the server response here
////            Toast.makeText(AddMerActivity.this, "Image uploaded to server", Toast.LENGTH_SHORT).show();
//        }
//    }
//
//    private String bitmapToBase64(Bitmap bitmap) {
//        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
//        byte[] byteArray = byteArrayOutputStream.toByteArray();
//        return Base64.encodeToString(byteArray, Base64.DEFAULT);
//    }
//
//    private String sendImageToServer(String imageData) {
//        ImageRequest imageRequest = new ImageRequest();
//        imageRequest.setBase64Image(imageData);
////        imageRequest.setName(merchandise.getFirstImage());
//        String imageJson = new Gson().toJson(imageRequest);
//        OkHttpUtil.getInstance().doPostJson("/mer/uploadImage", new DoCallBack() {
//            @Override
//            public void onSuccess(String result) {
//                Log.d("tag", "UploadImage" + result);
//                EditMerStockActivity.this.finish();
//            }
//
//            @Override
//            public void onError(Exception e) {
//                Toast.makeText(EditMerStockActivity.this, "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
//                handler.postDelayed(EditMerStockActivity.this::finish, 2000);
//            }
//        }, imageJson);
//        return "Server response: Image send";
//    }


}